package com.itheima.common;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author itheima
 * @Date 2022/4/29 14:58
 */
public class AuthHandlerInterceptor implements HandlerInterceptor {
    /**
     * preHandle: 在controller中方法执行之前作用
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("AuthHandlerInterceptor.preHandle");
        //true：则会放行，然后执行目标方法sayHello（请求controller对象的方法）；false就不会执行sayHello（）

        /**
         * 目标：在执行sayHello()目标方法之前，获取参数name进行判断，是否等于“admin”
         */
        String name = request.getParameter("name");
        //name不等于“admin”，则返回false也就是不执行目标方法
        if (name == null || !name.equals("admin")) {
            request.setAttribute("message", "您没有权限访问该方法！！");
            request.getRequestDispatcher("/error").forward(request, response);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("AuthHandlerInterceptor.postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("AuthHandlerInterceptor.afterCompletion");
    }
}
